<template>
	<view class="page-container">
		<view class="main-content">
			<!-- 报销人基本信息 -->
			<view class="section-box mb-20">
				<view class="section-title">
					<u-icon name="account" color="#1E40AF" size="24" class="icon-mr"></u-icon>
					<text class="title-text">报销信息</text>
				</view>
				<u-form :model="formData" :rules="rules" ref="uForm" labelWidth="80" labelAlign="right"
					:borderBottom="true">
					<!-- 姓名输入框 -->
					<u-form-item label="姓名" prop="userName">
						<u-input v-model="formData.userName" placeholder="姓名"></u-input>
					</u-form-item>
					<!-- 身份证号输入框 -->
					<u-form-item label="身份证号" prop="identityCardNo">
						<u-input v-model="formData.identityCardNo" type="idcard" placeholder="身份证号"></u-input>
					</u-form-item>
					<!-- 报销单位 -->
					<u-form-item label="报销单位" @click="navigateToSelectDept">
						<u-input v-model="selectedUnit.agencyName" readonly placeholder="请选择报销单位">
							<template slot="suffix">
								<u-icon name="arrow-right" color="#999" size="16" ></u-icon>
							</template>
						</u-input>
					</u-form-item>
				</u-form>
			</view>

			<!-- 报销事由 -->
			<view class="section-box mb-20">
				<view class="section-title">
					<u-icon name="file-text" color="#1E40AF" size="24" class="icon-mr"></u-icon>
					<text class="title-text">报销事由</text>
				</view>
				<u--textarea v-model="reason" placeholder="请详细描述报销事由" count></u--textarea>
			</view>

			<!-- 财政票据列表 -->
			<view class="section-box mb-160">
				<view class="section-title">
					<u-icon name="order" color="#1E40AF" size="24" class="icon-mr"></u-icon>
					<text class="title-text">财政票据列表</text>
				</view>

				<!-- 票据列表 -->
				<view class="receipt-list">
					<!-- 循环票2 -->
					<view class="receipt-item" v-for="(item,index) in selectedBills" :key="index">
						<view class="delete-icon">
							<u-icon name="trash" color="#1E40AF" size="22" @click="deleteReceipt(index)"></u-icon>
						</view>
						<view class="receipt-info">
							<view class="info-row">
								<text class="info-label">票据号码：</text>
								<text class="info-value">{{item.eInvoiceNumber}}</text>
								<text class="receipt-amount">¥ {{(item.totalAmount).toFixed(2)}}</text>
							</view>

							<view class="info-row">
								<text class="info-label">开票日期：</text>
								<text class="info-value">{{item.issueDate}}</text>
							</view>

							<view class="info-row">
								<text class="info-label">开票单位：</text>
								<text class="info-value">{{item.invoicingPartyName}}</text>
							</view>
							<view class="info-row">
								<text class="info-label">票据类型：</text>
								<text class="info-value">{{item.eInvoiceName}}</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 添加票据按钮 -->
				<view class="add-receipt-btn" @click="navigateToSelectReceipt">
					<u-icon name="plus-circle-fill" color="#999" size="24" class="icon-mr"></u-icon>
					<text>添加财政票据</text>
				</view>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="total-amount">
				<text class="total-label">合计金额：</text>
				<text class="total-value">¥ {{allAmount}}</text>
			</view>
			<view class="submit-btn">
				<u-button type="primary" text="提交报销" @click="submitReimbursement"></u-button>
			</view>

		</view>

	</view>
</template>

<script>
	import {
		authorizeEInvoice
	} from '@/api/homeApi.js'
	export default {
		data() {
			return {
				formData: {
					userName: '',
					identityCardNo: '',
				},
				// 校验规则
				rules: {
					userName: [{
						required: true,
						message: '姓名不能为空',
						trigger: 'blur'
					}],
					identityCardNo: [{
							required: true,
							message: '身份证号不能为空',
							trigger: 'blur'
						},
						{
							validator: (rule, value, callback) => {
								// 18位身份证正则（基本格式）
								const idCardReg =
									/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;

								if (!value) {
									return callback(new Error('请输入身份证号'));
								}

								// 基本格式校验
								if (!idCardReg.test(value)) {
									return callback(new Error('请输入正确的身份证号格式'));
								}

								// 校验码验证（根据GB 11643-1999标准）
								const code = '10X98765432'; // 校验码对应值
								const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; // 加权因子
								let sum = 0;
								const idCardUpper = value.toUpperCase(); // 统一转为大写（处理x/X）

								// 计算前17位与加权因子的乘积和
								for (let i = 0; i < 17; i++) {
									sum += parseInt(idCardUpper[i], 10) * factor[i];
								}

								// 计算校验码
								const checkCode = code[sum % 11];
								if (idCardUpper[17] !== checkCode) {
									return callback(new Error('身份证号校验码错误，请检查'));
								}

								// 验证通过
								callback();
							},
							trigger: 'blur'
						}
					],
				},
				selectedBills: [],
				reason: '',
				selectedUnit: {},
				showReceiptModal: false,
				receiptForm: {
					type: '',
					number: '',
					amount: '',
					date: '',
					unit: ''
				},
				receiptTypeList: [{
						value: 'invoice',
						label: '电子发票'
					},
					{
						value: 'receipt',
						label: '财政收据'
					},
					{
						value: 'other',
						label: '其他票据'
					}
				]
			};
		},
		created() {
			console.log('用户信息', uni.getStorageSync('userInfo'))
			const userInfo = uni.getStorageSync('userInfo')
			this.formData.identityCardNo = userInfo.cardNo || ''
			this.selectedUnit = userInfo.unitDefault || {}
			this.formData.userName = uni.getStorageSync('account') || ''
		},
		onReady() {
			//onReady 为uni-app支持的生命周期之一
			this.$refs.uForm.setRules(this.rules)
		},
		onLoad() {
			console.log('==')
			uni.$on('selectedUnit', (data) => {
				this.selectedUnit = data
				console.log(this.selectedUnit);
			})
			uni.$on('selectedBills', (data) => {
				console.log('selectedBills', data);
				data.forEach(item => {
					const uniqueKey = this.getUniqueKey(item);
					// 判断选中数组中是否已存在该对象
					const isExisted = this.selectedBills.some(
						selected => this.getUniqueKey(selected) === uniqueKey
					);
					// 不存在则添加
					if (!isExisted) {
						this.selectedBills.push(item);
					}
				});
			})
		},
		computed: {

			allAmount() {
				const total = this.selectedBills.reduce((sum, item) => {
					// 确保 totalAmount 是数字，避免非数字导致的 NaN
					const num = Number(item.totalAmount) || 0;
					return sum + num;
				}, 0); // 初始值为 0
				return total.toFixed(2)
			}
		},
		methods: {
			/**
			 * 生成唯一标识
			 * @param {Object} item - 数组中的对象
			 * @returns {String} 唯一键（eInvoiceCode + eInvoiceNumber）
			 */
			getUniqueKey(item) {
				return `${item.eInvoiceCode}${item.eInvoiceNumber}`;
			},
			navigateBack() {
				uni.navigateBack();
			},
			navigateToSelectDept() {
				uni.navigateTo({
					url: '/pages/home/reimbursementUnit',
					success: () => {
						uni.$emit('pageName', 'billReimbursement')
					}
				});
			},
			navigateToSelectReceipt() {
				uni.navigateTo({
					url: '/pages/home/selectReceipt'
				});
			},
			deleteReceipt(index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除该票据吗？',
					success: (res)=> {
						if (res.confirm) {
							console.log('删除票据',index);
							this.selectedBills.splice(index, 1)
						}
					}
				});
			},
			async submitReimbursement() {
				console.log('提交报销');
				this.$refs.uForm.validate().then(async val => {
					if (Object.keys(this.selectedUnit).length == 0) {
						return this.$u.toast('请选择报销单位');
					}
					if (this.reason == '') {
						return this.$u.toast('请输入报销事由');
					}
					if (this.selectedBills.length == 0) {
						return this.$u.toast('请添加财政票据');
					}
					uni.showLoading({
						title: '加载中'
					})
					const res = await authorizeEInvoice({
						payerPartyName: this.formData.userName,
						payerPartyCode: this.formData.identityCardNo,
						supervisorAreaCode: this.selectedBills[0].eInvoiceCode.substring(0, 2),
						authorizedAcctId: this.selectedUnit.accountId,
						authorizedAreaCode: this.selectedUnit.areaCode,
						authorizedPartyCode: this.selectedUnit.agencyCode,
						authorizedPartyName: this.selectedUnit.agencyName,
						authorizeRemark: this.reason,
						eInvoiceList: this.selectedBills
					})
					if (res.result == 0) {
						uni.$u.toast('提交成功')
						this.selectedBills = []

						uni.hideLoading()
					} else {
						uni.$u.toast(res.message || '提交失败')
						uni.hideLoading()
					}
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			}
		}
	};
</script>

<style scoped>
	.page-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
	}

	.main-content {
		padding: 32rpx;
	}

	.section-box {
		background-color: #ffffff;
		border-radius: 24rpx;
		padding: 32rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
	}

	.section-title {
		display: flex;
		align-items: center;
		margin-bottom: 32rpx;
		font-weight: 600;
		color: #333333;
	}

	.icon-mr {
		margin-right: 16rpx;
	}

	.title-text {
		font-size: 32rpx;
	}

	.form-grid {
		display: grid;
		grid-template-columns: 1fr;
		gap: 32rpx;
	}

	.form-item {
		display: flex;
		align-items: center;
		padding-bottom: 32rpx;
		border-bottom: 2rpx solid #f2f2f2;
		position: relative;
	}

	.form-item:last-child {
		border-bottom: none;
	}

	.form-label {
		width: 160rpx;
		font-size: 28rpx;
		color: #666666;
	}

	.form-input {
		flex: 1;
		font-size: 28rpx;
		padding: 0;
		height: 72rpx;
	}

	.select-arrow {
		position: absolute;
		right: 0;
	}

	.reason-input {
		width: 100%;
		padding: 20rpx;
		background-color: #f9f9f9;
		border-radius: 16rpx;
		font-size: 28rpx;
	}

	.word-count {
		display: block;
		text-align: right;
		font-size: 24rpx;
		color: #999999;
		margin-top: 16rpx;
	}

	.receipt-list {
		margin-bottom: 40rpx;
	}

	.receipt-item {
		border: 2rpx solid #f2f2f2;
		border-radius: 16rpx;
		padding: 32rpx;
		margin-bottom: 32rpx;
		position: relative;
		transition: all 0.3s;
	}

	.receipt-item-hover {
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
	}

	.delete-icon {
		position: absolute;
		top: 5rpx;
		right: 10rpx;
	}

	.receipt-info {
		/* padding-right: 48rpx; */
		padding-top: 30rpx;
	}

	.info-row {
		display: flex;
		margin-bottom: 20rpx;
		font-size: 28rpx;
	}

	.info-row:last-child {
		margin-bottom: 0;
	}

	.info-label {
		display: inline-block;
		width: 120rpx;
		color: #666666;
		margin-right: 16rpx;
		white-space: nowrap;
	}

	.info-value {
		color: #333333;
		flex: 1;
	}

	.receipt-amount {
		color: #1E40AF;
		font-weight: 600;
	}

	.add-receipt-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		padding: 24rpx 0;
		border: 4rpx dashed #e0e0e0;
		border-radius: 16rpx;
		color: #999999;
		font-size: 28rpx;
		transition: all 0.3s;
	}

	.add-receipt-btn:hover {
		border-color: #1E40AF;
		color: #1E40AF;
	}

	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		border-top: 2rpx solid #f2f2f2;
		padding: 32rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05);
	}

	.total-amount {
		display: flex;
		align-items: center;
	}

	.total-label {
		font-size: 28rpx;
		color: #666666;
		margin-right: 16rpx;
	}

	.total-value {
		font-size: 36rpx;
		font-weight: 600;
		color: #1E40AF;
	}

	.submit-btn {
		width: 200rpx;
		height: 88rpx;
		border-radius: 16rpx;
		font-size: 32rpx;
	}


	.receipt-modal {
		padding: 40rpx;
	}

	.modal-content {
		display: flex;
		flex-direction: column;
	}

	.modal-title {
		font-size: 36rpx;
		font-weight: 600;
		margin-bottom: 40rpx;
		color: #333333;
	}

	.upload-area {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 40rpx;
		border: 4rpx dashed #e0e0e0;
		border-radius: 16rpx;
	}

	.upload-icon {
		margin-bottom: 20rpx;
	}

	.upload-text {
		font-size: 28rpx;
		color: #999999;
		margin-bottom: 10rpx;
	}

	.upload-hint {
		font-size: 24rpx;
		color: #cccccc;
	}

	.confirm-btn {
		width: 100%;
		height: 88rpx;
		background-color: #1E40AF;
		color: #ffffff;
		border-radius: 16rpx;
		margin-top: 40rpx;
	}

	/* 间距类 */
	.mb-20 {
		margin-bottom: 40rpx;
	}

	.mb-160 {
		margin-bottom: 320rpx;
	}
</style>